#include<iostream>
#include<unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include<string>
#include<cstring>

using namespace std;

#define N 2
#define NUM 1024

void Writer(int wfd)
{
    string s="hello,i am child";
    pid_t self=getpid();
    int num=1;
    char Buffer[NUM];
    while(1)
    {
        snprintf(Buffer,sizeof(Buffer),"%s-%d-%d",s.c_str(),self,num);
        num++;

        //cout<<Buffer<<endl;

        write(wfd,Buffer,strlen(Buffer));

        //sleep(1);
    }
}


void Reader(int rfd)
{
    char Buffer[NUM];
    while(1)
    {
        sleep(5);
        int n=read(rfd,Buffer,sizeof(Buffer));
        if(n!=0)
        {
            Buffer[n]=0;
        }

        cout<<Buffer<<endl;
        
    }
}


int main()
{
    //输出型参数
    int pipefd[N]={0};

    //建立管道
    int n=pipe(pipefd);
    if(n<0)
    {
        perror("pipe");
    }

    pid_t id=fork();
    if(id<0)
    {
        perror("fork");
    }
    else if(id==0)
    {
        //child
        close(pipefd[0]);

        Writer(pipefd[1]);
    }
    
    else 
    {
         //parent

        close(pipefd[1]);

        Reader(pipefd[0]);

        pid_t rid=waitpid(id,nullptr,0);
        if(rid<0)
        {
            perror("waitpid");
        }
    }
       
    return 0;
}